package studychinese.utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.widget.Toast;


import com.hschinese.pronunciation.activity.MyApplication;

import java.io.File;
import java.math.BigDecimal;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class AppUtils {

    /**
     * 是否是第一次加载应用
     *
     * @param context
     * @return
     */
    public static boolean isFirst(Context context) {
        String version = (String) SPUtils.get(context, "AppConfig", "version", getVersion());
        boolean isFirst = (boolean) SPUtils.get(context, "AppConfig", "isfirst", true);
        if (getVersion(context).equals(version) || isFirst) {
            SPUtils.put(context, "AppConfig", "version", getVersion(context));
            SPUtils.put(context, "AppConfig", "isfirst", false);
        }
        return isFirst;
    }

    /**
     * 用户是否已登录
     *
     * @return
     */
    public static boolean isLogin() {
        return (boolean) SPUtils.get(MyApplication.getInstance(), "AppConfig", "islogin", false);
    }



    /**
     * 改变用户登录状态
     *
     * @param context
     * @param loginStatus
     */
    public static void  changeLogin(Context context, boolean loginStatus) {
        SPUtils.put(context, "AppConfig", "islogin", loginStatus);
    }
    public static void  changeGenXin(Context context, boolean changeGenXin) {
        SPUtils.put(context, "AppConfig", "changeGenXin", changeGenXin);
    }
    public static boolean isGenXin() {
        return (boolean) SPUtils.get(MyApplication.getInstance(), "AppConfig", "changeGenXin", false);
    }

    public static boolean isLoginOverdue(Context context) {
        long overdueTime = 1000L * 60L * 60L * 24L * 30L;
        long currentTime = TimeUtil.getCurrentTimeInLong();
        long lastLoginTime = (long) SPUtils.get(context, "AppConfig", "lastLoginTime", currentTime);
        long subTime = currentTime - lastLoginTime;//20天的登录有效期
        return subTime < overdueTime;
    }






    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion() {
        try {
            PackageManager manager = MyApplication.getInstance().getPackageManager();
            PackageInfo info = manager.getPackageInfo(MyApplication.getInstance().getPackageName(), 0);
            return info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getVersion(Context context) {
        String version = "";
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            version = packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return version;
    }

    /**
     * 获取渠道名
     *
     * @param context 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
    public static String getChannelName(Context context) {
        if (context == null) {
            return null;
        }
        String channelName = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
                ApplicationInfo applicationInfo = packageManager.
                        getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        channelName = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));
                    }
                }

            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return channelName;
    }

    /*
    user_id + Ymd格式日期+beixincheng 然后进行2次MD5加密
    如果user_id = 1, 当前时间为2016年6月1日09:32:38
    Token = MD5(MD5(‘120150601beixincheng’))
    */






    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }

        return false;
    }
    private static long exitTime = 0;
    private static Boolean isExit = false;
    public static void exitApp(Context context) {

        Timer tExit = null;
        if (!isExit) {
            isExit = true; // 准备退出
            Toast.makeText(context, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
           //这写退出程序
            System.exit(0);
        }
    }
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "KB";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    /***
     * 获取应用缓存大小
     * @param file
     * @return
     * @throws Exception
     */
    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }
    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

}
